import { loginAPI, userInfoAPI } from '@/api/user'
import router from '@/router'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      tokenObj: {},
      userInfo: {}

    }
  },
  mutations: {
    logout (state) {
      state.tokenObj = {}
      state.userInfo = {}
      router.push('/login')
    },

    setToken (state, obj) {
      state.tokenObj = obj
    },
    setUserInfo (state, obj) {
      state.userInfo = obj
    }
  },
  actions: {
    async login (ctx, info) {
      try {
        const res = await loginAPI(info)
        ctx.commit('setToken', res.data)
        console.log(info)
        if (info.back) {
          router.push(info.back)
        } else {
          router.push('/layout/home')
        }
        Toast.success('登录成功')
      } catch {
        Toast.fail('登陆失败')
      }
    },
    async reqUserInfo (ctx) {
      if (!ctx.state.userInfo.name) {
        const res = await userInfoAPI()
        ctx.commit('setUserInfo', res.data)
      }
    }

  }
}
